package com.HuiShou.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

import com.HuiShou.config.OrderNoGenerator;
import com.HuiShou.domain.RecycleCategory;
import com.HuiShou.mapper.RecycleCategoryMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.HuiShou.mapper.UserOrderMapper;
import com.HuiShou.domain.UserOrder;
import com.HuiShou.service.IUserOrderService;

/**
 * 订单Service业务层处理
 * 
 * @author lyz
 * @date 2025-03-19
 */
@Service
public class UserOrderServiceImpl implements IUserOrderService 
{
    private static final Logger log = LoggerFactory.getLogger(UserOrderServiceImpl.class);
    @Autowired
    private UserOrderMapper userOrderMapper;

    @Autowired
    private RecycleCategoryMapper recycleCategoryMapper;


    /**
     * 查询订单
     * 
     * @param orderId 订单主键
     * @return 订单
     */
    @Override
    public UserOrder selectUserOrderByOrderId(String orderId)
    {
        return userOrderMapper.selectUserOrderByOrderId(orderId);
    }

    /**
     * 查询订单列表
     * 
     * @param userOrder 订单
     * @return 订单
     */
    @Override
    public List<UserOrder> selectUserOrderList(UserOrder userOrder)
    {
        return userOrderMapper.selectUserOrderList(userOrder);
    }

    /**
     * 新增订单
     * 
     * @param userOrder 订单
     * @return 结果
     */
    @Override
    public int insertUserOrder(UserOrder userOrder)
    {
        // 生成并设置订单号
        userOrder.setOrderNo(OrderNoGenerator.generateOrderNo());

        // 处理 confidence 保留3位小数
        if (userOrder.getConfidence() != null) {
            BigDecimal bd = new BigDecimal(userOrder.getConfidence().toString());
            bd = bd.setScale(3, RoundingMode.HALF_UP);
            userOrder.setConfidence(bd.doubleValue());
        }

        // 根据 labels 查询分类单价
        RecycleCategory category = recycleCategoryMapper.selectByCategoryCode(userOrder.getLabels());
        if (category != null && category.getUnitPrice() != null) {
            // 设置单价到 userOrder
            userOrder.setUnitPrice(category.getUnitPrice());
        }
        return userOrderMapper.insertUserOrder(userOrder);
    }

    /**
     * 修改订单
     * 
     * @param userOrder 订单
     * @return 结果
     */
    @Override
    public int updateUserOrder(UserOrder userOrder)
    {
        return userOrderMapper.updateUserOrder(userOrder);
    }

    /**
     * 批量删除订单
     * 
     * @param orderIds 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteUserOrderByOrderIds(String[] orderIds)
    {
        return userOrderMapper.deleteUserOrderByOrderIds(orderIds);
    }

    /**
     * 删除订单信息
     * 
     * @param orderId 订单主键
     * @return 结果
     */
    @Override
    public int deleteUserOrderByOrderId(String orderId)
    {
        return userOrderMapper.deleteUserOrderByOrderId(orderId);
    }
}
